import { defineComponent, computed, unref, ref, toRaw } from 'vue';
import './index.less';
import type { DeckDetail, ModifyDeck } from '/@/api/verse/model/deckModel';
import Title from '/@/views/verse/components/Title';
import { useGo } from '/@/hooks/web/usePage';
import { awaitWrap, getTokenUrl } from '/@/utils';
import { Field, Icon as VantIcon, Button } from 'vant';
import { Icon } from '/@/components/Icon';
import { useVerseStore } from '/@/store/modules/verse';
import FighterPopup from './components/FighterPopup';
import { useMessage } from '/@/hooks/web/useMessage';
import { CreateDeckApi, DeckDetailApi, ModifyDeckApi } from '/@/api/verse/deck';
import DeckSelectCardList from '/@/views/verse/components/DeckSelectCardList/DeckSelectCardList';
import { appShareUsing } from '/@/utils/appInteractive';

export default defineComponent({
  name: 'DeckCreatePage',
  props: {
    id: {
      type: String as PropType<string>,
      required: true,
    },
  },
  setup(props) {
    // 设置分享参数
    appShareUsing({} as any);

    const go = useGo();
    const { createLoadingToast, clearToast } = useMessage();
    const pageTile = computed(() => {
      const { id } = props;
      if (id) {
        return '修改套牌';
      }
      return '创建套牌';
    });
    const leftClick = () => {
      const { id } = props;
      verseStore.clearCreateDeckParams();
      if (id) {
        go(`/versedeck/${id}`, true);
        return '修改套牌';
      }
      go(getTokenUrl('/versedeck'), true);
    };
    const fighterState = ref(false);
    const verseStore = useVerseStore();

    const getDeckDetail = async () => {
      if (!props.id) {
        !verseStore.createDeck.deck_name ? (verseStore.createDeck.deck_name = '我的套牌') : null;
        return false;
      }
      const [error, data] = await awaitWrap(DeckDetailApi({ id: Number(props.id) }));
      if (error) {
        return;
      }
      const result = data as DeckDetail;
      !verseStore.createDeck.deck_name ? (verseStore.createDeck.deck_name = result.deck_name) : null;
      !verseStore.getCreateDeckParams.main_fighters.length
        ? verseStore.setCreateDeckFighter(result.main_fighters)
        : null;
      !verseStore.getCreateDeckParams.main_cards.length ? verseStore.setCreateDeckMainCard(result.main_cards) : null;
      !verseStore.getCreateDeckParams.other_cards.length ? verseStore.setCreateDeckOtherCard(result.other_cards) : null;
    };
    getDeckDetail();

    const confirm = () => {
      createLoadingToast({
        message: '保存中',
        overlay: true,
      });
      props.id ? modifyDeck() : createCard();
    };
    const modifyDeck = async () => {
      // clearToast();
      const result = toRaw(verseStore.getCreateDeckParams) as ModifyDeck;
      result.deck_name ? null : (result.deck_name = '我的套牌');
      result.id = Number(props.id);
      const [error] = await awaitWrap(ModifyDeckApi(result));
      if (error) {
        clearToast();
      }
      clearToast();
      verseStore.clearCreateDeckParams();
      go(`/versedeck/${result.id}`, true);
    };
    const createCard = async () => {
      const result = toRaw(verseStore.getCreateDeckParams);
      result.deck_name ? null : (result.deck_name = '我的套牌');
      const [error] = await awaitWrap(CreateDeckApi(result));
      if (error) {
        clearToast();
      }
      clearToast();
      verseStore.clearCreateDeckParams();
      go(getTokenUrl('/versedeck'), true);
    };

    const inputSlot = {
      'left-icon': () => {
        return <Icon icon={'ri:edit-2-fill'} />;
      },
    };
    return () => (
      <div class={'deck-create-page'}>
        <Title title={unref(pageTile)} leftArrow onLeftClick={leftClick} />
        <div class={'create-container'}>
          <div class={'flex deck-name'}>
            <div class={'input-item justify-between mr-lg'}>
              <Field
                label={'套牌名称'}
                v-slots={inputSlot}
                labelClass={'input-label'}
                clearable
                v-model={[verseStore.getCreateDeckParams.deck_name]}
              ></Field>
            </div>
            <Button type={'primary'} round onClick={confirm}>
              {props.id ? '确认修改' : '确认创建'}
            </Button>
          </div>
          <div class={'input-item fighters flex items-baseline'}>
            <div
              class={'label-item flex items-center'}
              onClick={() => {
                fighterState.value = true;
              }}
            >
              <Icon icon={'ic:baseline-filter-alt'} />
              <span class={'input-label'}>选择主战者</span>
            </div>
            <ul class={'fighters-list'}>
              {verseStore.getCreateDeckParams.main_fighters.map((item, index) => {
                return (
                  <li class={'fighters-item flex items-center'}>
                    <span class={'f-name'}>
                      {item.card_career}-{item.name}
                    </span>
                    <VantIcon
                      name={'clear'}
                      onClick={() => {
                        verseStore.getCreateDeckParams.main_fighters.splice(index, 1);
                      }}
                    />
                  </li>
                );
              })}
            </ul>
          </div>
          <DeckSelectCardList
            mainCards={verseStore.getCreateDeckParams.main_cards}
            otherCards={verseStore.getCreateDeckParams.other_cards}
          />
        </div>
        <ul class={'action-area flex items-center justify-between'}>
          <li
            class={'exprot flex flex-col items-center'}
            onClick={() => {
              go('/versedeckcard/main');
            }}
          >
            <Icon class={'!text-xl mb-sm'} icon={'carbon:add-filled'} />
            <span>添加主牌</span>
          </li>
          <li
            class={'modify flex flex-col items-center'}
            onClick={() => {
              go('/versedeckcard/other');
            }}
          >
            <Icon class={'!text-xl mb-sm'} icon={'carbon:add-filled'} />
            <span>添加额外牌</span>
          </li>
        </ul>
        <FighterPopup v-model={[fighterState.value, 'show']} />
      </div>
    );
  },
});
